#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

# python imports
import logging
from os import path
from urllib import unquote, unquote_plus

# django imports
from django.utils import simplejson

# google imports
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.runtime import DeadlineExceededError
  
# textlocutor imports
import core_settings
import core
from core.models import CoreUser
from core.utils import send_message
from sms.models import SmsFixture

class SmsHandler(core.BaseRequestHandler):
    def get(self):
        user = users.get_current_user()
        info = self.init_fixtures(user)
        if self.bad_init:
            return
        coreuser = CoreUser.all().filter('user =', users.get_current_user()).get()
        smsuser = coreuser.smsfixture_set.get()
        template_values = {'user' : coreuser,
                           'smsuser': smsuser,
                           'ext_list': core_settings.EXTRA_APPS,
                           'base_url': self.request.host_url,
                           'logout_url': users.CreateLogoutURL(self.request.uri),
                           }
        if info:
            template_values.update(info)
        self.generate(template_values, 'sms_main.html')

    def post(self): 
        user = users.get_current_user()

        sender_coreuser = CoreUser.all().filter('user =', user).get()
        sender_smsuser = sender_coreuser.smsfixture_set.get()
        receiver_coreuser = CoreUser.all().filter('user =', users.User(self.request.POST['email'])).get()
        receiver_smsuser = receiver_coreuser.smsfixture_set.get()

        if sender_smsuser.key() in receiver_smsuser.users_allowed:
            if len(self.request.POST['message']) > 240:
                message = "You can't send a message with more than 240 characters"
            else:
                try:
                    send_message(receiver_coreuser, user.nickname() + ':' + self.request.POST['message'])
                    message = """Message sent. textLocutor! has just created an event in the receiver's gCalendar, by the way isn't guarantied the arrival in the destination mobile."""
                except DeadlineExceededError:
                    message = """The application seems to be experiencing problems. Please, try again."""
        else:
            # You are not allowed to send sms to this user
            message = 'You are not allowed to send sms to this user. You need his/her permission.'
    
        self.response.out.write(simplejson.dumps({'message': message}))


class SmsUser(core.BaseRequestHandler):

    def get(self):
        user = users.get_current_user()
        coreuser = CoreUser.all().filter('user =', user).get()
        smsuser = SmsFixture.all().filter('coreuser =', coreuser).get()
        users_dict = {'allowed': [],
                      'waiting': []}
        
        for u in smsuser.users_allowed:
            try:
                # TODO: Attribute error?
                u_aux = db.get(u)
                users_dict['allowed'].append({'email': u_aux.coreuser.user.email(),
                                              'nick': u_aux.coreuser.nick,
                                              'active': u_aux.active})
            except AttributeError:
                smsuser.users_allowed.remove(u)
                smsuser.put()
                
        for u in smsuser.users_waiting:
            try:
                users_dict['waiting'].append(db.get(u).coreuser.user.email())
            except AttributeError:
                smsuser.users_waiting.remove(u)
                smsuser.put()

        self.response.out.write(simplejson.dumps(users_dict))        

    def post(self, email):
        current_user = users.get_current_user()
        email_aux = unquote(email)
        user = users.User(email_aux)

        coreuser = CoreUser.all().filter('user =', user).get()
        smsuser = SmsFixture.all().filter('coreuser =', coreuser).get()

        message = 'ok'
        if smsuser is None:
            message = "%s can't be allowed while hasn't an activated account." % email_aux
        else:
            current_coreuser = CoreUser.all().filter('user =', current_user).get()
            current_smsuser = SmsFixture.all().filter('coreuser =', current_coreuser).get()

            if smsuser.key() in current_smsuser.users_waiting:
                smsuser.users_allowed.append(current_smsuser.key())
                smsuser.put()

                if not smsuser.key() in current_smsuser.users_allowed:
                    current_smsuser.users_allowed.append(smsuser.key())

                current_smsuser.users_waiting.remove(smsuser.key())
                current_smsuser.put()

                message = 'You have allowed %s to send you sms.' % email_aux
            else:
                message = "%s hasn't made the required request previously." % email_aux
        
        response = {'email': smsuser.coreuser.user.email(), 'nick': smsuser.coreuser.nick, 'active': smsuser.active}
        self.response.out.write(simplejson.dumps(response))
         
    def put(self, email):
        current_user = users.get_current_user()
        email_aux = unquote(email)
        user = users.User(email_aux)

        coreuser = CoreUser.all().filter('user =', user).get()
    
        message = 'ok'
        if coreuser is None:
            message = "The request couldn't be send, %s doesn't belong to textLocutor!" % email_aux
        else:
            smsuser = SmsFixture.all().filter('coreuser =', coreuser).get()

            if smsuser is None:
                message = "%s hasn't an activated account." % email_aux
            else:
                current_coreuser = CoreUser.all().filter('user =', current_user).get()
                current_smsuser = SmsFixture.all().filter('coreuser =', current_coreuser).get()

                if smsuser.key() in current_smsuser.users_allowed:
                    message = '%s is already in your allowed users list' % email_aux
                elif smsuser.key() in current_smsuser.users_waiting:
                    message = '%s is already in your waiting users list' % email_aux
                elif current_smsuser.key() in smsuser.users_waiting:
                    message = 'You have already send to %s a request' % email_aux
                else:
                    smsuser.users_waiting.append(current_smsuser.key())
                    smsuser.put()
                    message = '%s has been asked for let you send sms.' % email_aux
        response = {'message': message, 'username': email_aux}
        self.response.out.write(simplejson.dumps(response))

    def delete(self, email):
        current_user = users.get_current_user()
        current_coreuser = CoreUser.all().filter('user =', current_user).get()
        email_aux = unquote(email)
        user = users.User(email_aux)
        coreuser = CoreUser.all().filter('user =', user).get()
        current_smsuser = SmsFixture.all().filter('coreuser =', current_coreuser).get()
        smsuser = SmsFixture.all().filter('coreuser =', coreuser).get()

        message = 'ok'
        if coreuser is None:
            message = "The request couldn't be processed. %s doesn't belong to textLocutor!" % email_aux
        else:
            if not (smsuser.key() in (current_smsuser.users_allowed or
                                       current_smsuser.users_waiting)):
                message = "%s has neither requested you nor belongs to your allowed list of sms senders" % email_aux
            else:
                try:
                    smsuser.users_allowed.remove(current_smsuser.key())
                except ValueError: # If the element doesn't belong to the list
                    pass
                try:
                    smsuser.users_waiting.remove(current_smsuser.key())
                except ValueError:
                    pass
                smsuser.put()
                try:
                    current_smsuser.users_allowed.remove(smsuser.key())
                except ValueError:
                    pass
                try:
                    current_smsuser.users_waiting.remove(smsuser.key())
                except ValueError:
                    pass
                current_smsuser.put()

        response = {'message': message, 'email': email_aux}
        self.response.out.write(simplejson.dumps(response)) 
